#!/bin/bash

set -o errexit

cluster="proxy-protocol"
test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions

set_debug

if [[ $IMAGE_PXC =~ 5\.7 ]]; then
	echo "Skipping proxy-protocol test because 5.7 doesn't support it!"
	exit 0
fi

prepare_config() {
	desc "prepare config"
	nodes=$(kubectl get nodes | grep -v "NAME" | grep -v 'master' | awk '{print $1}')
	if [ $(printf "${nodes}\n" | wc -l) -lt 3 ]; then
		echo "3 nodes are expected for this test to run."
		exit 1
	fi
	haproxy_node=$(echo "${nodes}" | tail -n1)
	pxc_node=$(echo "${nodes}" | tail -n2 | head -n1)
	client_node=$(echo "${nodes}" | tail -n3 | head -n1)
	cat ${test_dir}/conf/${cluster}.yml \
		| $sed -e "s#kubernetes.io/hostname:.*-node1\$#kubernetes.io/hostname: ${haproxy_node}#" \
		| $sed -e "s#kubernetes.io/hostname:.*-node2\$#kubernetes.io/hostname: ${pxc_node}#" >${tmp_dir}/${cluster}.yml
	cat ${test_dir}/conf/client.yml | $sed -e "s#kubernetes.io/hostname:.*-node3\$#kubernetes.io/hostname: ${client_node}#" >${tmp_dir}/client.yml
}

prepare_config
create_infra ${namespace}

desc 'create first PXC cluster'
spinup_pxc "${cluster}" "${tmp_dir}/${cluster}.yml" "3" "15" "${conf_dir}/secrets.yml" "${tmp_dir}/client.yml" "33062"
sleep 120

client_ip=$(kubectl_bin get pods --selector=name=pxc-client -o 'jsonpath={.items[].status.podIP}')
if [ ${EKS} -eq 1 ]; then
	node_name=$(kubectl_bin get pods --selector=name=pxc-client -o 'jsonpath={.items[].spec.nodeName}')
	client_ip=$(kubectl_bin get nodes ${node_name} -o 'jsonpath={.status.addresses[?(@.type == "ExternalIP")].address}')
fi
if [[ -n ${OPENSHIFT} ]]; then
	pod_name=$(kubectl_bin get pods --selector=name=pxc-client -o 'jsonpath={.items[].metadata.name}')
	client_ip=$(kubectl_bin exec ${pod_name} -- curl -s ifconfig.io)
fi

service_ip=$(get_service_endpoint proxy-protocol-haproxy)

desc 'check if service and statefulset created with expected config'
compare_kubectl statefulset/${cluster}-pxc
compare_kubectl statefulset/${cluster}-haproxy
compare_kubectl service/${cluster}-pxc
compare_kubectl service/${cluster}-haproxy
compare_kubectl service/${cluster}-haproxy-replicas

desc 'check if client ip visible in mysql processlist'
nr_queries=$(run_mysql "show processlist;" "-h ${service_ip} -uroot -proot_password" | grep "show processlist" | grep -c "${client_ip}")
if [ ${nr_queries} -ne 1 ]; then
	echo "Client IP ${client_ip} is not found in process list!"
	exit 1
fi

desc 'cleanup'
kubectl_bin delete -f ${test_dir}/conf/${cluster}.yml
destroy ${namespace}
desc "test passed"
